﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using KL.UFrame.Core.Configuration;

namespace KL.UFrame.Api.Controllers
{
    public class FileController : Controller
    {
        
        [System.Web.Mvc.HttpPost]
        public async Task<JsonResult> Upload([FromBody]HttpPostedFileBase file)
        {
            string filePath;

            if (Request.Files.Count > 0)
            {
                filePath = await SaveAsync(Request.Files[0]);
            }
            else if (Request.InputStream != null)
            {
                filePath = await SaveAsync(Request.InputStream);
            }
            else
            {
                return Json(new { Code = -1, Message = "没有检测的文件数据" });
            }

            return Json(new { Code = 0, Message = filePath });
        }

        private async Task<string> SaveAsync(HttpPostedFileBase file)
        {
            string filePath;
            string localPath;

            GetFilePath(file.FileName, out filePath, out localPath);

            await Task.Run(() => file.SaveAs(localPath));
            return filePath;
        }

        public async Task<string> SaveAsync(Stream inputStream)
        {
            string filePath;
            string localPath;

            GetFilePath(string.Empty, out filePath, out localPath);
            await Task.Run(() =>
            {
                using (inputStream)
                {
                    using (var flieStream = new FileStream(localPath, FileMode.Create))
                    {
                        inputStream.CopyTo(flieStream);
                    }
                }
            });
            return filePath;
        }

        private void GetFilePath(string fileName, out string filePath, out string localPath)
        {
            var path = AppConfiguration.FileUploadPath + (DateTime.Today.Year * 100 + DateTime.Today.Month) + "/";
            localPath = Server.MapPath("~" + path);
            if (!Directory.Exists(localPath))
            {
                Directory.CreateDirectory(localPath);
            }
            string ext;
            if (string.IsNullOrEmpty(fileName) || !fileName.Contains("."))
            {
                ext = ".jpg";
            }
            else
            {
                ext = fileName.Substring(fileName.LastIndexOf('.'));
            }
            filePath = path + Guid.NewGuid().ToString("N") + ext;
            localPath = Server.MapPath("~" + filePath);
        }
    }
}